import { Component, OnInit, Injector, Output, EventEmitter, Input } from '@angular/core';
import { Service } from '../../../server/server';
import { CudTableService } from '../../../public/serve/cud-table/cud-table.service';
import { HintsService } from '../../../public/serve/hints/hints.service';
import { RemoveTableService } from '../../../public/serve/remove-table/remove-table.service';
import { InitService } from '../../../public/serve/init/init.service';
import { keyword } from './keyword.data';
import { appKeywordUrl } from './keyword.url';
import { BaseTreeComponent } from '../../../public/components/base-tree/base-tree.component';
import { HttpClient } from '@angular/common/http';
import { TreeNode } from '../../../public/common/api';
import {appSynonymUrl} from '../../../synonym/synonym.url';
declare var $:any;
@Component({
  selector: 'app-left-keyword',
  templateUrl: './left-keyword.component.html',
  styleUrls: ['./left-keyword.component.css']
})

export class LeftKeywordComponent implements OnInit {

  @Input() tabCheckStatus: any;
  @Input() searchData: any;
  @Input() status: any  = '';
  @Input() labelId: any  = '';
  @Input() internalParam: any  = '';
  @Input() referenceIndexing: any = '';
  currentThemeWordsNode = -1;
  total: number = 0;
  naturalNum: number = 0;
  totalRecords: number;
  public totalItems: number;
  changeCheck: any = 1;
  loading: boolean = false;

  keywordTabVal: Array<object>;
  themeTagListVal : Array<object>;

  isSelectAll: boolean = false;
  isChose: boolean = false;

  files: TreeNode[];
  cols: any[];
  productId:any = ''; //相当于主题词表的id

  right: any = {
    "keyword": {},
    "keywordTrial": {},
    "keywordUnreviewed": {}
  };

  public getCheckedTableId = [];
  selectedData  : TreeNode[] = [];

  constructor(
    private server: Service,
    public request: CudTableService,
    private tableListService: CudTableService,
    private hintsService: HintsService,
    private removeTableService: RemoveTableService,
    public initService: InitService,
    private http: HttpClient
  ) { 
    this.right = $.extend(this.right, server.getRight());
  }

  ngOnInit() {
      //默认进来选中第一个

  }

  _infoThemeTab(productId){
    keyword.retrieval.status='';
    keyword.retrieval.labelId='';
    keyword.retrieval.queryCriteria = '';
    keyword.pagination.pageNo = 1;
    keyword.pagination.pageSize = 20;
    this.productId = productId;
    this._themeTagList();
    this._keyworkTabList();
  }

  /**
   * 查询主题词列表
   */
  _keyworkTabList() {
    //this.loading = true;
    let data = this._tableData();
    this.request.postRequest(this.server.baseUrl +appKeywordUrl.getThemeWordsList, data).then((res: any) => {
      if (res.result_code === '0000') {
        this.keywordTabVal = res.result;
        this.files = this._processTreeData(this.keywordTabVal, 'themeWordsId', 'parentid', 'name');
        this.totalRecords = res.length;
        this.total = res.length;
        if(res.result.length > 0){
            this.currentThemeWordsNode = res.result[0].themeWordsId;
            this._selectThemeWordsNode(res.result[0].themeWordsId,res.result[0].themeTableId,res.result[0].name);
        }
      } else {
        this.hintsService.messages(res.message, res.result_code);
      }
      //this.loading = false;
      this._cancelChecked();
      return;
    })
      .catch((err: any) => {
        this.hintsService.messages("error", "error");
        this._cancelChecked();
        //this.loading = false;
        return;
      });
  }

  /**
   * 点击图标显示子级的主题词
   * @param queryData 
   * @param node 
   */
  public getChildrenList(queryData, node) {
    this.request.postRequest(this.server.baseUrl +appKeywordUrl.getThemeWordsList, queryData).then((data: any) => {

      if (data.result_code == '0000') {
        node['children'] = this._toTree(data.result, node['themeWordsId'], 'themeWordsId', 'parentid', 'name');
        this.files = [...this.files];
        return false;
      } else {
        this.hintsService.messages(data.message, data.result_code);
      }

    }).catch();
  }

  _processTreeData(list: Array<any>, idName, parentIdName, labelName): Array<any> {
    return this._toTree(list, '0', idName, parentIdName, labelName);
  }

  _toTree(list: Array<any>, topId = '0', idName, parentIdName, labelName) {
    let idKey = idName;
    let result = [];
    for (let item of list) {
      if (item[parentIdName] == topId) {

        let children = {};
        let expandedIcon = 'fa fa-folder-open';
        let collapsedIcon = 'fa fa-folder';
        let leaf = false;

        if (item['child'] == '0') {
          expandedIcon = '';
          collapsedIcon = '';
          leaf = true;
        }

        let dataArr = {
          'data': {
            label: item['name'],
            data: item['themeTableId'],
            expandedIcon: expandedIcon,
            collapsedIcon: collapsedIcon,

            arrchildid: item['arrchildid'],
            arrparentid: item['arrparentid'],
            checkStatus: item['checkStatus'],
            createBy: item['createBy'],
            child: item['child'],
            name: item['name'],
            createTime: item['createTime'],
            status: item['status'],
            themeCode: item['themeCode'],
            themeGroupId: item['themeGroupId'],
            themeTableId: item['themeTableId'],
            themeWordsId: item['themeWordsId'],
            parentid: item['parentid'],
            description: item['description'],
            labelId: item['labelId'],
            labelName: item['labelName'],
          },
          'leaf': leaf,
          'themeWordsId': item['themeWordsId']
        };

        result.push(dataArr);
      }
    }
    return result;
  }


  /**
     * 全选
     * @param bool
     * @param keywordTabVal
     */
  _selectAll(bool, keywordTabVal) {
     keywordTabVal.forEach(str => {
         this._nodeSelect(bool, {id:str.data['themeWordsId'],name:str.data['name']});
      });
     this.files.forEach((str,index) => {
         this.files[index]['data']['isChecked'] = bool;
      });
      this.files = [...this.files];
  }

  /**
   * 单选
   * @param bool
   * @param themeWordsId
   * @param length
   */
  _chose(bool, themeWordsId, length) {
    this.isSelectAll = this.removeTableService.keywordRemoveChose(bool, themeWordsId, length)['bool'];
  }

  /**
   * 重置表格复选框、选中的ID
   */
  private _cancelChecked() {
    this.isChose = this.isSelectAll = false;
    this.removeTableService._clearId("themeWordsId");
  }

  //查询参数
  private _tableData() {
    return {
      token: keyword.retrieval.token,
      pageNo: keyword.pagination.pageNo,
      pageSize: keyword.pagination.pageSize,
      status: keyword.retrieval.status,
      labelId: keyword.retrieval.labelId,
      themeCode: keyword.retrieval.themeCode,
      checkStatus: this.tabCheckStatus,
      startTime: keyword.retrieval.startTime,
      endTime: keyword.retrieval.endTime,
      queryCriteria: keyword.retrieval.queryCriteria,
      themeTableId: this.productId,
      parentId: keyword.retrieval.parentId
    }
  }

  onNodeExpand(event) {
    const node = event.node;
    let queryData = {
      token: keyword.retrieval.token,
      //checkStatus   : this.tabCheckStatus,
      themeTableId: keyword.retrieval.themeTableId,
      pageNo: 1,
      pageSize: 9999,
      parentId: node.themeWordsId
    };
    this.getChildrenList(queryData, node);
  }

  /**
   * 获取主题词标签列表
   */
  _themeTagList(){
    let data = {
      token         : keyword.retrieval.token,
      pageNo        : 1,
      pageSize      : 999,
    };
    this.request.postRequest(this.server.baseUrl +appKeywordUrl.getThemeWordsLabelList,data).then((res:any) => {
      if (res.result_code === '0000') {
        this.themeTagListVal = res.result;
      }else{
        this.hintsService.messages(res.message,res.result_code);
      }
      return;
    })
    .catch((err: any)=>{
      this.hintsService.messages("error","error");
      return;
    });
  }


    /**
     * 分页
     * @param pagination
     */
    _pagination(pagination: Array<any>) {
        keyword.pagination.pageNo = pagination[0].pageNumber;
        keyword.pagination.pageSize   = pagination[0].pageSize;
        keyword.pagination.naturalNum = (keyword.pagination.pageNo - 1) * keyword.pagination.pageSize;
        this._keyworkTabList();
    }

    //搜索
    search() {
        keyword.retrieval.queryCriteria = this.searchData;
        keyword.retrieval.status = this.status;
        keyword.retrieval.labelId = this.labelId;
        this._keyworkTabList();
    }
    //响应搜索
    changesearch() {
        this.search();
    }

    //验证是否有重复的选择
    _isNodeSelect(id){
        let flag = false;

        this.getCheckedTableId.forEach(str => {
            if (Number(id) === Number(str['val'])) {
                flag = true;
            }
        });

        return flag;
    }

    checkNode(str) {
        if(this.selectedData){
            this.selectedData.splice(this.selectedData.findIndex(item => item['id'] === str), 1);
        }
    }

    /**
     * 选中的节点
     * @param event
     * @param id
     */
    _nodeSelect(bool,event) {

        if(bool == true){
            if(this.getCheckedTableId.length > 0){
                let flag = this._isNodeSelect(event.id);
                if(flag){
                    this.getCheckedTableId.splice(this.getCheckedTableId.findIndex(item => item['val'] === event.id), 1);
                }else{
                    this.selectedData.push(event);
                }
            }else{
                this.selectedData.push(event);
            }
            let arr = {
                'txt':event.name,
                'val':event.id
            };
            this.getCheckedTableId.push(arr);
        }else{
            if(this.getCheckedTableId.length > 0){
                $("#checked_"+event.id).prop("checked",'');
                //删除
                this.checkNode(event.id);
            }
            this.getCheckedTableId.splice(this.getCheckedTableId.findIndex(item => item['val'] === event.id), 1);
        }
    }

    /**
     * 确定标引
     */
    _addKeywordTheme(){
        if (this.getCheckedTableId.length > 0) {
            this.server.onSubmitAppViewEmit.emit(this.getCheckedTableId);
            this.getCheckedTableId = [];
        }
    }

    _selectThemeWordsNode(themeWordsId,themeTableId,themeWordsName){
      //选中的主题词id
      let obj = {
        themeWordsId : themeWordsId,
        themeTableId : themeTableId,
        themeWordsName : themeWordsName
      };
      this.currentThemeWordsNode = themeWordsId;
      if(this.referenceIndexing == 1){
        this.server.referenceInternalThemeWordsLeftEmit.emit(obj);
        this.server.referenceInternalThemeWordsTablesRelEmit.emit(2);
        this.server.referenceThemeInternalAttributeEmit.emit(obj);//参考标引属性
      }else{
        this.server.internalThemeWordsLeftEmit.emit(obj);
        this.server.internalThemeWordsTablesRelEmit.emit(2);
        this.server.internalThemeInternalAttributeEmit.emit(obj);//标引属性
      }
    }

}
